﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Carer.Crm.Authorize
{
    public class SessionAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool flag = true;
            if (httpContext.Session["UserId"] == null || httpContext.Session["UserId"].ToString().Length == 0)
            {
                httpContext.Response.StatusCode = 401;//无权限状态码
                flag = false;
            }

            return flag;
        }


        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);
            if (filterContext.HttpContext.Response.StatusCode == 401)
            {
                filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl + "?returnUrl=" + filterContext.HttpContext.Request.UrlReferrer);
            }

        }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            //if (filterContext.HttpContext.Response.StatusCode == 401)
            //{
            //    if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            //    {
            //        filterContext.Result = new RedirectResult("/");
            //    }
            //    else
            //    {
            //        //跳转到 web.config 中定义的  loginUrl="~/"
            //        filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl + "?returnUrl=" + filterContext.HttpContext.Request.UrlReferrer);
            //    }
            //}
        }

    }
}
